import React, { useState, useEffect } from "react";
import { useDispatch, useSelector } from 'react-redux';
import { CRow, CFormInput, CButton, CCol, CFormLabel, CCard, CFormSelect } from '@coreui/react';
import { clearDoctorData } from '../../actions/auth';

const AddDoctor = () => {    
    const [username, setUsername] = useState('');
    const [doctorData, setDoctorData] = useState({});
    const [message, setMessage] = useState('');
    const [modalityList, setModalityList] = useState([]);
    const [selectedModality, setSelectedModality] = useState(null);
    const token = useSelector((state) => state.token);
    const storedDoctorData = useSelector((state) => state.doctorData);
    const dispatch = useDispatch();

    const fetchModalityList = async () => {
        try {
            const response = await fetch(`${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/modality/`, {
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
            });
            const data = await response.json();
            setModalityList(data);
        } catch (error) {
            console.error("Failed to fetch modality list:", error);
        }
    };

    const handleSubmitFind = async () => {
        try {
            const searchUrl = username? `${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/users/find_by_username?username=${encodeURIComponent(username)}` : `${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/users/find_by_username?username=${encodeURIComponent(doctorData.username)}`;

        const response = await fetch(searchUrl, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
        
        });
        const data = await response.json();
        setUsername('')
        setMessage('')
        if (data.username) {
            setDoctorData(data);
            setSelectedModality(data.modality);
        } else {
            setMessage('Пользователь не найден');
        }
        } catch (error) {
            console.error("Failed to find user:", error);
            setMessage('Ошибка при поиске пользователя');
        }
    };

    const handleCreate = async (e) => {
        e.preventDefault();
        let url = `${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/users/`;
        let modalityId = isNaN(parseInt(selectedModality))? 1 : parseInt(selectedModality);

        console.log(parseInt(selectedModality))
        let body = {
            username: doctorData.username,
            login: doctorData.username,
            password: doctorData.username,
            role_id: 4,
            modality_id: modalityId,
            employment_rate: doctorData.employment_rate || '',
            start_work: doctorData.start_work || '2024-06-08',
            status: doctorData.status || ''
        };
    
        try {
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(body)
            });

            if (!response.ok) {
                const errorResponse = await response.json();
                throw new Error(errorResponse.detail);
            }

            const result = await response.json();
            if (result) {
                setMessage('Успешно создано');
                setUsername(result.username);
                handleSubmitFind()
            } else {
                setMessage(result.detail);
            }
        } catch (error) {
            setMessage(error.message);
        }
    };

    
    const handleSave = async (e) => {
        e.preventDefault();
        let url = `${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/users/${doctorData.id}`;
        let body = {
            username: doctorData.username,
            modality_id: parseInt(selectedModality),
            additional_modality: doctorData.additional_modality? doctorData.additional_modality.map(modality => modality.id) : [],
            employment_rate: doctorData.employment_rate,
            start_work: doctorData.start_work,
            status: doctorData.status
        };
    
        try {
            const response = await fetch(url, {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(body)
            });
            const result = await response.json();
            if (result) {
                setMessage('Успешно сохранено');
                setUsername(result.username)
                handleSubmitFind()
            } else {
                setMessage('Ошибка при сохранении');
            }
        } catch (error) {
            console.error("Failed to save user:", error);
            setMessage('Ошибка при сохранении пользователя');
        }
    };
    
    const handleInputChange = (event, key) => {
        const value = event.target.value;
        if (key === 'employment_rate') {
            if (isNaN(value)) {
                alert("Ставка должна быть числом");
                event.target.value = '';
                return;
            }
        }
        setDoctorData(prevState => ({
        ...prevState,
            [key]: value
        }));
    };

    const handleModalityChange = (e) => {
        setSelectedModality(e.target.value);
        console.log(e.target.value)
    };

    useEffect(() => {
        if (storedDoctorData) {
            setDoctorData(storedDoctorData);
        }
        dispatch(clearDoctorData())
        fetchModalityList();
    }, []); 
    
    return (
        <div>
            <h1>Добавление кадровых данных</h1>
            <br></br>
            <form onSubmit={handleSubmitFind}>
                <CRow>
                    <CCol xs={6}>
                        <CFormInput
                            type="text"
                            placeholder="Фамилия Имя Отчество"
                            aria-label="Username"
                            value={username}
                            onChange={(e) => setUsername(e.target.value)}
                        />
                    </CCol>
                    <CCol xs={3}>
                        <CButton color="light" variant="outline" type="submit">Найти</CButton>
                    </CCol>
                </CRow>
                <br></br>
                <CRow>
                    
                </CRow>
            </form>
            <br></br>
            <CCard style={{ width: '45rem' }}>
                <CRow className="m-3">
                    <CFormLabel htmlFor="username" className="col-sm-3 col-form-label">ФИО</CFormLabel>
                    <CCol sm={9}>
                        <CFormInput
                            type="text"
                            id="username"
                            // defaultValue={doctorData.username}
                            value={doctorData.username}
                            onChange={(e) => handleInputChange(e, 'username')}
                        />
                    </CCol>
                </CRow>
                <CRow className="m-3">
                    <CFormLabel htmlFor="modality" className="col-sm-3 col-form-label">Модальность</CFormLabel>
                    <CCol sm={9}>
                    <CFormSelect
                        aria-label="Выберите модальность"
                        options={
                            Object.keys(doctorData).length === 0? [] : modalityList.map((modality) => ({
                                label: modality.name,
                                value: modality.id.toString(),
                            }))
                        }
                        value={selectedModality}
                        onChange={handleModalityChange}
                    />


                    </CCol>
                </CRow>

                <CRow className="m-3">
                    <CFormLabel htmlFor="employmentRate" className="col-sm-3 col-form-label">Ставка</CFormLabel>
                    <CCol sm={9}>
                        <CFormInput type="text" id="employmentRate" defaultValue={doctorData.employment_rate} onChange={(e) => handleInputChange(e, 'employment_rate')} />
                    </CCol>
                </CRow>

                <CRow className="m-3">
                    <CFormLabel htmlFor="startWork" className="col-sm-3 col-form-label">Начало работы</CFormLabel>
                    <CCol sm={9}>
                        <CFormInput type="text" id="startWork" defaultValue={doctorData.start_work} onChange={(e) => handleInputChange(e, 'start_work')} />
                    </CCol>
                </CRow>

                <CRow className="m-3">
                    <CFormLabel htmlFor="status" className="col-sm-3 col-form-label">Статус</CFormLabel>
                    <CCol sm={9}>
                        <CFormInput type="text" id="status" defaultValue={doctorData.status} onChange={(e) => handleInputChange(e, 'status')} />
                    </CCol>
                </CRow>

                <CRow className="m-3">
                    <CFormLabel htmlFor="additionalModality" className="col-sm-3 col-form-label">Дополнительные модальности</CFormLabel>
                    <CCol sm={9}>
                        <CFormInput
                            type="text"
                            id="additionalModality"
                            defaultValue={doctorData.additional_modality && doctorData.additional_modality.length > 0? 
                                doctorData.additional_modality.map((modality, index) => modality.name).join(', ') :
                                ""}
                            onChange={(e) => handleInputChange(e, 'additional_modality')}
                        />
                    </CCol>
                </CRow>

                
            </CCard>
            <br></br>
            <CRow>
                <CCol xs={5}>
                    <CButton color="light" variant="outline" type="submit" onClick={handleSave}>Сохранить</CButton>
                </CCol>
                <CCol xs={3}>
                    <CButton color="light" variant="outline" type="submit" onClick={handleCreate}>Создать</CButton>
                </CCol>
            </CRow>
            
            <CRow>
                <CFormLabel htmlFor="staticEmail" className="col-sm-12 col-form-label">{message}</CFormLabel>
            </CRow>
        </div>
    );
};

export default AddDoctor;
